package com.mq.java.test;

import com.mq.common.MqConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zhd
 * @date 2019/08/17
 * RabbitMQ事物，不推荐使用，性能比较差
 **/
public class ProducerTx {

    public static void main(String[] args) {

        try {
            // 连接到RabbitMQ
            Connection connection = MqConnectionUtils.getConnection();

            Channel channel = connection.createChannel();

            String exchangeName = "tx-exchange";
            channel.exchangeDeclare(exchangeName,
                    BuiltinExchangeType.DIRECT,
                    false,
                    false,
                    false,
                    null);

            //声明事物
            channel.txSelect();
            channel.basicPublish(exchangeName,
                    "tx-routingKey",
                    false,
                    false,
                    MessageProperties.TEXT_PLAIN,
                    "1111".getBytes());
            //提交事物
            channel.txCommit();

            // 回滚事物
            channel.txRollback();

            // 渠道关闭
            channel.close();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
